//导入依赖项
import { saveAs } from "file-saver";
import * as XLSX from "xlsx/xlsx.mjs";

const isDOM =
  typeof HTMLElement === "object"
    ? function (obj) {
        return obj instanceof HTMLElement;
      }
    : function (obj) {
        return obj && typeof obj === "object" && obj.nodeType === 1 && typeof obj.nodeName === "string";
      };

//导入uuid.js工具
/**
 * elemet-ui el-table数据导出为xlsx表格
 * @param {*} dom Element-UI el-table组件
 */
export default function (dom, _options) {
  let options = {
    fileName: +new Date(),
    ..._options,
  };

  let originalDom;
  if (typeof dom === "string") {
    originalDom = document.querySelector(dom);
  } else {
    originalDom = isDOM(dom) ? dom : dom.$el;
  }

  let targetDom = originalDom.cloneNode(true);
  let fixedTable = targetDom.querySelectorAll(".el-table__fixed");
  let fixedRightTable = targetDom.querySelectorAll(".el-table__fixed-right");
  [...fixedTable, ...fixedRightTable].forEach((element) => {
    element.remove();
  });

  //根据table生成Book工作簿
  let wb = XLSX.utils.table_to_book(targetDom);
  console.log(wb);
  //将Book工作簿作为输出
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  //尝试将当前table内容保存为excel文件
  try {
    saveAs(
      //被导出的blob二进制对象
      new Blob([wbout], { type: "application/octet-stream" }),
      //导出文件的名称+后缀名
      options.fileName + ".xlsx"
    );
  } catch (e) {
    if (typeof console != "undefined") console.log(e, wbout);
  }
}
